package com.gcit.seniorWish.web.modular.examinee.controller;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gcit.seniorWish.core.base.controller.BaseController;
import com.gcit.seniorWish.core.base.tips.ErrorTip;
import com.gcit.seniorWish.core.base.tips.Tip;
import com.gcit.seniorWish.core.exception.GunsException;
import com.gcit.seniorWish.core.util.FileUtil;
import com.gcit.seniorWish.core.util.ToolUtil;

import com.gcit.seniorWish.web.config.properties.BussProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.ui.Model;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;

import com.gcit.seniorWish.web.common.constant.enums.UserTypeEnum;
import com.gcit.seniorWish.web.common.constant.factory.PageFactory;
import com.gcit.seniorWish.web.common.persistence.dao.SeniorExamineeMapper;
import com.gcit.seniorWish.web.common.persistence.model.SeniorExaminee;
import com.gcit.seniorWish.web.common.persistence.model.User;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorExamineeService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolClassService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolService;
import com.gcit.seniorWish.web.modular.examinee.warpper.ExamineeWarpper;
import com.gcit.seniorWish.web.modular.system.service.IUserMgrService;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 考生信息控制器
 *
 * @author tonglu
 * @Date 2018-03-20 10:52:55
 */
@Controller
@RequestMapping("/seniorExaminee")
public class SeniorExamineeController extends BaseController {

	private String PREFIX = "/examinee/examinee";

	@Autowired
	private ISeniorExamineeService seniorExamineeService;

	@Resource
	private SeniorExamineeMapper seniorExamineeMapper;

	@Autowired
	private ISeniorSchoolClassService seniorSchoolClassService;

	@Autowired
	ISeniorSchoolService seniorSchoolService;

	@Autowired
	private IUserMgrService userMgrService;

	@Autowired
	private BussProperties bussProperties;

	/**
	 * 数据列表
	 */
	@RequestMapping("")
	public String index(Model model) {
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), ShiroKit.getUser().getClassId()));
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", null);
		} else {
			model.addAttribute("schoolu", null);
			model.addAttribute("classu", null);
		}
		return PREFIX + "/examinee.html";
	}

	/**
	 * 获取考生列表
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(String seniorSchoolId,String seniorClassId,
			@RequestParam(required = false) String examCardNumber,
			@RequestParam(required = false) String studentName) {
		Page<Map<String, Object>> page = new PageFactory().defaultPage();
		EntityWrapper<SeniorExaminee> ew = new EntityWrapper<SeniorExaminee>();
		if(StrUtil.isNotBlank(seniorSchoolId)){
			ew.eq("senior_school_id",seniorSchoolId);
		}
		if(StrUtil.isNotBlank(seniorClassId)){
			ew.eq("senior_class_id",seniorClassId);
		}
		if (StrUtil.isNotBlank(examCardNumber))
			ew.like("exam_card_number", examCardNumber);
		if (StrUtil.isNotBlank(studentName))
			ew.like("student_name", studentName);
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			ew.eq("senior_school_id", ShiroKit.getUser().getSchoolId());
			ew.eq("senior_class_id", ShiroKit.getUser().getClassId());
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			ew.eq("senior_school_id", ShiroKit.getUser().getSchoolId());
		}
		seniorExamineeService.selectMapsPage(page, ew);
		page.setRecords((List<Map<String, Object>>) new ExamineeWarpper(page.getRecords()).warp());
		return packForBT(page);
	}

	/**
	 * 跳转到查编辑页面
	 */
	@RequestMapping("/edit")
	public String edit(SeniorExaminee examinee, Model model) {
		examinee = seniorExamineeMapper.selectById(examinee.getId());
		if (examinee == null) {
			examinee = new SeniorExaminee();
			model.addAttribute("examineeschools", null);
			model.addAttribute("examineeclasses", null);
		} else {
			model.addAttribute("examineeschools",
					seniorSchoolService.listSchoolForSelect2(null, examinee.getSeniorSchoolId()));
			model.addAttribute("examineeclasses", seniorSchoolClassService.listSchoolClassForSelect2(null,
					examinee.getSeniorSchoolId(), examinee.getSeniorClassId()));
		}
		model.addAttribute("examinee", examinee);
		return PREFIX + "/examineeEdit.html";
	}

	/**
	 * 考生保存
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/save")
	@ResponseBody
	public Tip save(SeniorExaminee examinee) {
		EntityWrapper<SeniorExaminee> ew = new EntityWrapper<>();
		ew.eq("exam_card_number",examinee.getExamCardNumber());
		//当id存在时，判断准考证号是否存在需要排除该记录
		if(StrUtil.isNotBlank(examinee.getId())){
			ew.ne("id",examinee.getId());
		}
		if (this.seniorExamineeService.selectCount(ew) > 0) {// 该准考证号已存在
			throw new GunsException(BizExceptionEnum.EXAM_CARD_NUMBER_EXIST);
		}
		//当id存在时
		if(StrUtil.isNotBlank(examinee.getId())){
			SeniorExaminee existExaminee = seniorExamineeService.selectOne(Condition.create().setSqlSelect("exam_card_number").eq("id",examinee.getId()));
			//当准考证号修改时，判断修改后生成的用户名在用户表中是否存在
			if(!existExaminee.getExamCardNumber().equals(examinee.getExamCardNumber())){
				if (userMgrService.selectCount(Condition.create().eq("account", examinee.getExamCardNumber())) > 0) {// 用户名已存在
					throw new GunsException(BizExceptionEnum.USER_ALREADY_REG);
				}
			}
		}else{
			if (userMgrService.selectCount(Condition.create().eq("account", examinee.getExamCardNumber())) > 0) {// 用户名已存在
				throw new GunsException(BizExceptionEnum.USER_ALREADY_REG);
			}
		}
		seniorExamineeService.mergeExaminee(examinee);
		return SUCCESS_TIP;
	}

	/**
	 * 删除考生
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/remove")
	@ResponseBody
	public Tip remove(@RequestParam String examineeId) {
		if (ToolUtil.isEmpty(examineeId)) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}
		// 删除对应的用户
		SeniorExaminee exam = seniorExamineeMapper.selectById(examineeId);
		this.seniorExamineeMapper.deleteById(examineeId);
		User user = userMgrService.selectOne(Condition.create().eq("account", exam.getExamCardNumber()));
		if (user != null) {
			userMgrService.deleteUser(user.getId());
		}
		return SUCCESS_TIP;
	}

	/**
	 * 根据模板导入学生数据
	 * 
	 * @param
	 * @author tonglu
	 * @date 2018-02-26 下午 1:56
	 */
	@RequestMapping(method = RequestMethod.POST, path = "/importExaminee")
	@ResponseBody
	public Object importActivityPlan(@RequestPart("file") MultipartFile excelFile) {
		try {
			String msg = seniorExamineeService.importExaminee(excelFile.getInputStream());
			if (StrUtil.isBlank(msg)) {
				msg = "导入成功";
			}
			// 返回导入结果
			return new Tip(200, msg);
		} catch (IOException e) {
			e.printStackTrace();
			return new ErrorTip(BizExceptionEnum.SERVER_ERROR.getCode(), BizExceptionEnum.SERVER_ERROR.getMessage());
		}
	}


	/**
	 * 导出学生信息(包括志愿信息)
	 *
	 * @param
	 * @author gaozhichang
	 * @date 2018-03-28 上午 9:44
	 */
	@RequestMapping("/exportExaminee")
	public void exportExaminee(String seniorSchoolId, String seniorClassId,String examCardNumber, Integer confirmStatus) {

		EntityWrapper<SeniorExaminee> ew = new EntityWrapper<SeniorExaminee>();
		//针对seniorExaminee表的查询条件
		ew.setParamAlias("seniorExamineeWrapper");
		if (StrUtil.isNotBlank(seniorSchoolId)) {
			ew.eq("senior_school_id", seniorSchoolId);
		}
		if (seniorClassId != null) {
			ew.eq("senior_class_id", seniorClassId);
		}
		if (examCardNumber != null) {
			ew.eq("exam_card_number", examCardNumber);
		}
		if(confirmStatus != null) {
			if (confirmStatus != null) {
				ew.eq("confirm_status",0);
			} else {
				ew.eq("confirm_status",1);
			}
		}
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			ew.eq("senior_school_id", ShiroKit.getUser().getSchoolId());
			ew.eq("senior_class_id", ShiroKit.getUser().getClassId());
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			ew.eq("senior_school_id", ShiroKit.getUser().getSchoolId());
		}
		//获取servletResponse，设置response参数
		HttpServletResponse response = this.getHttpServletResponse();
		try {
			seniorExamineeService.exportExaminee(response,seniorSchoolId,seniorClassId,examCardNumber,confirmStatus);
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	*返回学生头像
	* @param
	* @author gaozhichang
	* @date 2018-04-12 上午 10:25
	*/
	@RequestMapping("/examineeHeadPic/{archivesNumber}")
	public void examineeHeadPic(@PathVariable("archivesNumber") String archivesNumber, HttpServletResponse response) {
		String path = bussProperties.getExamineeHeadPicPath() + archivesNumber + ".jpg";
		try {
			byte[] bytes = FileUtil.toByteArray(path);
			response.getOutputStream().write(bytes);
		}catch (Exception e){
			//如果找不到图片就返回一个默认图片
			try {
				response.sendRedirect("/static/portal/images/none.gif");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

}
